package com.tbit.main.controller;

import com.tbit.common.utils.TraceUtil;
import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.ResponseCode;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.Image;
import com.tbit.main.service.AccountService;
import com.tbit.main.service.ImageService;
import com.tbit.main.service.TokenService;
import com.tbit.main.util.Assert;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.LogUtil;
import com.tbit.main.util.OutputUtil;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * 图片
 *
 * @author Leon
 * 2019年11月16日 下午2:36:24
 */
@RestController
@RequestMapping("/image")
public class ImageController {
    @Autowired
    private ImageService imageService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AccountService accountService;

    /**
     * 添加
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/addOss")
    public JsonResult add(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws FileUploadException, IOException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        /* 判断是否是文件上传 */
        if (multipartResolver.isMultipart(request)) {
            String imageId = null;

            /* 得到所有的文件 */
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next().toString());

                if (file.getSize() > 10 * 1024 * 1024) {
                    throw new BaseException("Image.tooBig");
                }

                InputStream input = file.getInputStream();
                byte[] imageContent = new byte[input.available()];
                input.read(imageContent, 0, input.available());

                /**存储图片*/
                Image image = new Image();
                imageId = UUID.randomUUID().toString();
                image.setImageId(imageId);
                image.setCreateTime(DateTimeUtil.getNowTime());
                image.setImageContent(imageContent);
                image.setImageType("image/jpg");

                LogUtil.info("图片大小:" + imageContent.length);

                imageService.add(image);
            }

            /**判断是否有图片*/
            if (imageId == null) {
                throw new BaseException("Image.need");
            }

            return JsonResult.succ(imageId);
        } else {
            throw new BaseException("Image.need");
        }
    }

    /**
     * 查看图片
     */
    @RequestMapping("/getByImageId")
    public void getByImageId(String imageId, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            /* 校验 */
            Assert.hasLength(imageId, "Image.id.notNull");

            /**从数据库加载图片*/
            Image image = imageService.getByImageId(imageId);
            if (image == null) {
                throw new BaseException("Image.notExist");
            }

            if (image.getImageContent().length > 0) {
                response.setContentType(image.getImageType());
                OutputStream out = response.getOutputStream();
                try {
                    out.write(image.getImageContent());
                } catch (Exception e) {
                    e.getMessage();
                } finally {
                    out.flush();
                    out.close();
                    image = null;
                }
            }
        } catch (BaseException e) {
            ResponseCode.printException(map, e);
            OutputUtil.renderText(request, response, map);
        }
    }


    /**
     * 阿里云oss上传
     */

    @RequestMapping("/add")
    public JsonResult addOss(String token, HttpServletRequest request) throws Exception {
        MultipartFile file = null;

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        /* 判断是否是文件上传 */
        if (multipartResolver.isMultipart(request)) {
            String imageId = null;

            /* 得到所有的文件 */
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                file = multiRequest.getFile(iter.next().toString());
            }
        } else {
            throw new BaseException("Image.need");
        }

        AccountUser accountUser = tokenService.getAccount(token);
        return JsonResult.succ(imageService.addAdvert(accountService.getByAccountAndType(accountUser.getAccountId(), 1).getAccountId(), file));
    }

    /**
     * 阿里云oss上传
     */
    @PostMapping("/uploadToOss")
    public JsonResult<String> addOss(@NotBlank String token,@NotNull MultipartFile file){
        AccountUser accountUser = tokenService.getAccount(token);
        try {
            String result = imageService.addAdvert(accountService.getByAccountAndType(accountUser.getAccountId(), 1).getAccountId(), file);
            return JsonResult.succ(result);
        } catch (Exception e) {
            return JsonResult.fail(ResponseCode.FAIL,e.getMessage(), TraceUtil.getTraceIdByLocal());
        }
    }
}